package problem5;

//5.最长回文串
//https://leetcode.cn/problems/longest-palindromic-substring/

//动态规划解

class Solution {
    public String longestPalindrome(String s) {
        int n = s.length();
        int[][] dp = new int[n+1][n+1];
        int maxlen = 0, l = 0, r = 0;
        for(int i = n-1; i>=0; i--) {
            for(int j = i; j<n; j++) {
                if(s.charAt(i) == s.charAt(j)) {
                    if(i == j) dp[i][j] =1;
                    else if(i+1 == j) dp[i][j] = 2;
                    else if(dp[i+1][j-1] != 0) dp[i][j] = Math.max(dp[i+1][j-1] + 2, dp[i][j]);
                }
                if(dp[i][j] > maxlen) {
                    l = i;
                    r = j;
                    maxlen = dp[i][j];
                }
            }
        }
        return s.substring(l, r+1);
    }
}

/*

dp[i][j]: i~j之间的字符中, 能否构成回文串, 0:不能

*/